import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/finished_in_scan_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_move_line_odoo_api.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/finish_in.dart';
import 'package:flutter_admin/models/odoo/stock_move_line.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input_num.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:qrscan/qrscan.dart' as scanner;
import 'package:quiver/strings.dart';

class LocationInConfirmation extends StatefulWidget {
  LocationInConfirmation({Key? key,this.stockMoveLine,this.isProcess = false}) : super(key: key);

  StockMoveLine? stockMoveLine;

  bool isProcess;

  @override
  _LocationInConfirmationState createState() => _LocationInConfirmationState();
}

class _LocationInConfirmationState extends State<LocationInConfirmation> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  StockMoveLine stockMoveLine = StockMoveLine();
  String? locationNextName;
  List<SelectOptionVO> locationNextList = [];
  List<SelectOptionVO> locationList = [];
  UserInfo userInfo = StoreUtil.getCurrentUserInfo();
  List<SelectOptionVO> jobJsonList = [];
  @override
  void initState() {
    super.initState();
    stockMoveLine = widget.stockMoveLine == null?StockMoveLine():widget.stockMoveLine!;
    stockMoveLine.qtyDone = num.parse(stockMoveLine.planQty!);
    _loadSelectVO();
  }

  _loadSelectVO() async {
    if(!widget.isProcess){
      locationNextList = await DynamicDataApi.getModelSelect(
          model: 'stock.location',
          name: 'complete_name',
          // tag: "complete_name",
          key: 'father_locaiton',
          val: int.parse(stockMoveLine.locationId!)
      );
    }else{
      ResponseBodyApi res = await StockMoveLineOdooApi.getLocation(userInfo.userId);
      if (res.success!){
        for(var i = 0; i < res.data.length; i++){
          locationList.add(SelectOptionVO(value: res.data[i]["locaiton_id"].toString(),label: res.data[i]["locaiton_name"]));
        }
        if(res.data.length == 1){
          stockMoveLine.locationId = res.data[0]["location_id"].toString();
          locationNextList = await DynamicDataApi.getModelSelect(
              model: 'stock.location',
              name: 'complete_name',
              // tag: "complete_name",
              key: 'father_locaiton',
              val: int.parse(stockMoveLine.locationId!)
          );
        }
      }
    }
    setState(() {});
  }

  _getJobJson() async{
    if(!isBlank(stockMoveLine.jobType) && !isBlank(stockMoveLine.locationId)){
      jobJsonList = [];

    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            label: '入库类型',
            enable: false,
            value: stockMoveLine.jobTypeName,
          ),
          CryInput(
            label: '生产订单号',
            value: stockMoveLine.productionNo,
            onSaved: (v) {
              stockMoveLine.productionNo = v;
            },
          ),

          widget.isProcess?CrySelect(
            label: '入库库房',
            dataList: locationList,
            value: stockMoveLine.locationId,
            onChange: (v) async {
              if (stockMoveLine.locationId != v) {
                formKey.currentState!.save();
                stockMoveLine.locationId = v;
                stockMoveLine.jobJson = null;
                stockMoveLine.shelves = null;
                jobJsonList = [];
                locationNextList = [];
                try {
                  locationNextList = await DynamicDataApi.getModelSelect(
                      model: 'stock.location',
                      name: 'complete_name',
                      // tag: "complete_name",
                      key: 'father_locaiton',
                      val: int.parse(stockMoveLine.locationId!)
                  );
                  ResponseBodyApi res = await StockMoveLineOdooApi.getJobJson(
                      typeId: stockMoveLine.jobType,
                      scene: "入库",
                      locationId: stockMoveLine.locationId
                  );
                  if (res.success!){
                    for(var i = 0; i < res.data.length; i++){
                      jobJsonList.add(SelectOptionVO(value: res.data[i].toString(),label: res.data[i]));
                    }
                  }
                } catch (e) {
                  // jobJsonList = [];
                }
                setState(() {});
              }
            },
            onSaved: (v) {
              stockMoveLine.locationId = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ):CryInput(
            label: '入库库房',
            enable: false,
            value: stockMoveLine.locationName,
            onSaved: (v) {
              stockMoveLine.locationName = v;
            },
          ),
          widget.isProcess?CrySelect(
            label: '发方位置',
            dataList: jobJsonList,
            value: stockMoveLine.jobJson,
            onSaved: (v) {
              stockMoveLine.jobJson = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ):CryInput(
            label: '发放位置',
            enable: false,
            value: stockMoveLine.jobJson,
          ),
          CrySelect(
            label: '库位',
            dataList: locationNextList,
            value: stockMoveLine.shelves,
            onSaved: (v) {
              stockMoveLine.shelves = v;
            },
          ),
          CryInput(
            label: '物料编码',
            enable: false,
            value: stockMoveLine.productCode,
            onSaved: (v) {
              stockMoveLine.productCode = v;
            },
          ),
          CryInput(
            label: '物料名称',
            enable: false,
            value: stockMoveLine.productName,
            onSaved: (v) {
              stockMoveLine.productName = v;
            },
          ),
          CryInput(
            label: '规格型号',
            enable: false,
            value: stockMoveLine.productDesc,
            onSaved: (v) {
              stockMoveLine.productDesc = v;
            },
          ),
          CryInputNum(
            label: '数量',
            value: stockMoveLine.qtyDone,
            onSaved: (v) {
              stockMoveLine.qtyDone = v;
            },
          ),
          CryInput(
            label: '单位',
            enable: false,
            value: stockMoveLine.productUomName,
            onSaved: (v) {
              stockMoveLine.productUomName = v;
            },
          ),
          CryInput(
            label: '备注',
            value: stockMoveLine.remark,
            onSaved: (v) {
              stockMoveLine.remark = v;
            },
          ),
        ],
      ),
    );

    var footerBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: "确定",
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();
            if(widget.isProcess){
              StockMoveLineOdooApi.inCreate(stockMoveLine.toOdooMap()).then((ResponseBodyApi res) {
                if (!res.success!) {
                  return;
                }
                Navigator.pop(context, true);
                CryUtils.message(S.of(context).saved);
              });
            }else{
              StockMoveLineOdooApi.saveOrUpdate(stockMoveLine.toOdooMap()).then((ResponseBodyApi res) {
                if (!res.success!) {
                  return;
                }
                Navigator.pop(context, true);
                CryUtils.message(S.of(context).saved);
              });
            }

          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        title: Text("入库确认"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: footerBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
  }

}
